#include <assert.h>
#include "../Include/HttpRequest.h"
#include "../Include/HttpRequestImpl.h"

CHttpRequest::CHttpRequest()
{
    m_lRequestCount = 0L;
    m_nThreadCount = 1;
    m_vecAffinity.push_back(-1);
}

CHttpRequest::~CHttpRequest()
{
    for (auto pEngine : m_vecEngine)
    {
        delete pEngine;
    }
    m_vecEngine.clear();
}

void CHttpRequest::SetThreadCount(Int32 nCount)
{
    assert(nCount > 0);
    m_nThreadCount = nCount;
}

void CHttpRequest::SetAffinity(const vector<Int32> &vecAffinity)
{
    assert(!vecAffinity.empty());
    m_vecAffinity = vecAffinity;
}

Bool CHttpRequest::Initialize()
{
    Bool bSuccess = False;

    do
    {
        Int32 nAffinitySize = m_vecAffinity.size();
        for (Int32 i = 0; i < m_nThreadCount; i++)
        {
            Int32 nAffinity = m_vecAffinity[i % nAffinitySize];
            CEventThread *pThread = new CEventThread();
            if (!pThread->Initialize(nAffinity))
            {
                break;
            }

            m_vecEngine.push_back(pThread);
        }

        if ((Int32)m_vecEngine.size() != m_nThreadCount)
        {
            break;
        }

        bSuccess = True;
    } while (0);

    return bSuccess;
}

void CHttpRequest::Request(const CHttpRequestParam &param)
{
    Int64 lRequestSeq = __sync_add_and_fetch(&m_lRequestCount, 1);
    CEventEngine *pEngine = m_vecEngine[lRequestSeq % m_nThreadCount];

    auto pRequest = new CHttpRequestImpl(pEngine);
    pRequest->Initialize(param);
    pRequest->Release();
}
